package com.yikome.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import cn.hutool.core.util.StrUtil;

@ControllerAdvice(annotations = RestController.class)
public class ApiResultHandler implements ResponseBodyAdvice<Object> {


    /**
     * 对所有RestController的接口方法进行拦截
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

    	//if(StrUtil.equalsIgnoreCase("application/x-javascript", selectedContentType.toString())) return body ; 
    	
    	if(body != null && body.getClass().equals(String.class)) return body ; 
    	
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        
        ApiResult out = new ApiResult();
        
        out.setCode(ApiResult.CODE_SUCCESS);
        out.setMessage("服务器响应成功");
        out.setDatas(body);
        
        return out;
    }

}